import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author gao
 * @time 2021/12/24 11:44:39
 */
@WebServlet({"/login.do", "/logout.do"})
public class AuthServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String servletPath = req.getServletPath();

        if ("/login.do".equals(servletPath)) {
            String username = req.getParameter("username");
            String password = req.getParameter("password");

            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);

            try {
                subject.login(token);
                resp.sendRedirect("/s/index.jsp");
                return;
            } catch (Exception e) {
                e.printStackTrace();
                resp.sendRedirect("/s/login.jsp");
                return;
            }

        }

        if ("/logout.do".equals(servletPath)) {
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            resp.sendRedirect("/s/login.jsp");
        }

    }
}
